package com.llf.Blog.Controller;


import com.llf.Blog.Pojo.User;

import com.llf.Blog.Service.UserService;
import com.llf.Blog.ServiceImpl.UserServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;


/**
 * @author machenike
 */
@Controller
@Api(value = "提供获取用户信息接口",tags = "用户信息管理")
public class UserController {

    @Autowired
    private UserService userService;
    /**
     * 跳转关于我页面
     */
    @ApiOperation("关于我页面跳转接口")
    @GetMapping("/toAbout")
    public String toAbout(){
        return "about";
    }

    /**
     * 跳转登录页面 如果登录 跳转到后台主页
     * 如果没有登录 就跳转登录页
     * @param session
     * @return
     */
    @ApiOperation("登录页面跳转接口")
   @GetMapping("/toLogin")
    public String toLogin(HttpSession session){
        if (session.getAttribute("username")!=null){
            return "redirect:admin/toBlogManage/1";
        }else {
        return "admin/login";
        }
    }

    /**
     * 后台登陆  登陆成功 将用户信息存入session 并将账号密码存入Shiro令牌
     * @param username 用户名
     * @param password 密码
     * @param model
     * @param session  session对象
     * @return
     */
    @ApiOperation("用户登录接口")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "string",name = "username", value = "用户名",required = true),
            @ApiImplicitParam(dataType = "string",name = "password", value = "密 码",required = true)
    })
    @PostMapping("/login")
    public String login(String username, String password, Model model, HttpSession session) {

        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户数据到令牌  token 令牌
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        User user = userService.getUser(username);
        if (!StringUtils.isEmpty(user)){
            session.setAttribute("user",user);
        }
        //执行登录操作
        try{
            subject.login(token);
            session.setAttribute("username",username);
            return "redirect:/toIndex";
        }catch ( UnknownAccountException e){
            //用户名不存在
            model.addAttribute("t","账号或密码错误");
            return "admin/login";
        }catch (IncorrectCredentialsException e){
            //密码错误

            model.addAttribute("t","账号或密码错误");
            return "admin/login";
        }
        }



    /**
     * 前往修改密码
     */
    @GetMapping("/admin/toUpdatePassword")
    public String toUpdatePassword(){
        return "admin/updatePassword";
    }



    /****
     * 修改用户密码
     * @param attributes 提示信息
     * @param user 用户对象
     * @return
     */
    @ApiOperation("用户修改密码接口")
    @PostMapping("/UpdatePassword")
    public String UpdatePassword(RedirectAttributes attributes,@RequestBody User user){
        int i = userService.updatePassword(user);
        if (i!=0){
            attributes.addFlashAttribute("message","密码修改成功");
        }else {
            try {
                throw new Exception("系统错误");
            } catch (Exception e) {
                e.printStackTrace();
            }
            attributes.addFlashAttribute("message","网路延迟，修改密码失败");
        }
        return "redirect:/admin/toBlogManage/1";

    }


    /**
     * 注销
     * @return
     */
    @ApiOperation("注销接口")
    @GetMapping("/toLogOut")
    public String logOut(){
        return "index";

    }


    /****
     * 前往注册页面
     */
    @ApiOperation("注册页面跳转")
    @RequestMapping("/toRegiest")
    public String   toRegiest(){
        return "admin/regiest";
    }


    /****
     * 用户注册
     * @param user 用户信息
     * @return
     */
    @ApiOperation("用户注册接口")
    @PostMapping("/regiest")
    @ResponseBody
    public HashMap<String,Object> regiest(@RequestBody User user){
        HashMap map = userService.insertUser(user);
        try {
          if (map.get("data").equals("用户名已存在")){
              throw  new Exception("用户名已存在");
          }else if (map.get("data").equals("用户昵称已存在")){
              throw  new Exception("用户昵称已存在");
          }
        } catch (Exception e) {
                e.printStackTrace();
            }
        return map;
    }

    /**
     * 根据登录状态 做出相应跳转
     * **/

    @ApiOperation("用户跳转登录/注销接口")
    @GetMapping("/toLoginOut")
    public String toLoginOut(HttpSession session){
        if (StringUtils.isEmpty(session.getAttribute("user"))){
            return "admin/login";
        }
        return "redirect:/toLogOut";

    }


    /**
     * 后台跳转
     * **/
    @ApiOperation("后台跳转")
    @GetMapping("/toBlogManage")
    public String toBlogManage(){
        return "redirect:/admin/toBlogManage/1";
    }
}
